/**
 * createby : JinxLbj
 * date : 2018/8/10
 * desc : 进程操作实现类
 **/

package com.example.demo.common.service.impl;

import com.example.demo.biz.project.entity.ProcessEntity;
import com.example.demo.common.service.ProcessService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ProcessServiceImpl implements ProcessService {

    private static Map<String, ProcessEntity> processMap = new HashMap<>();


    @Override
    public void putProcess(Process process, String processKey, String command) {
        //获取PID
        List<Long> pids = new ArrayList<>();
        Stream<ProcessHandle> stream = process.descendants();
        List<ProcessHandle> list = stream.collect(Collectors.toList());
        for (ProcessHandle processHandle:
                list) {
            pids.add(processHandle.pid());
        }
        pids.add(process.pid());
        processMap.put(processKey, new ProcessEntity(process, processKey, pids, command, new Date()));
    }

    @Override
    public boolean killProcess(String processKey) {
        ProcessEntity processEntity = processMap.get(processKey);
        Runtime rt = Runtime.getRuntime();
        Process killProcess = null;
        try {
            for (int i = 0; i < processEntity.getPid().size(); i++) {
                killProcess = rt.exec(new String[]{"sh", "-c", "kill -s 9 " + processEntity.getPid().get(i)});
                System.out.println(" >>Destroy " + "sh" + "-c" + "kill -s 9 " + processEntity.getPid().get(i));
            }
            killProcess.waitFor();
            killProcess.destroy();
            return true;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<String> getProcesss() {
        List<String> list = new ArrayList<>();
        Set<Map.Entry<String, ProcessEntity>> set = processMap.entrySet();
        for (Map.Entry<String, ProcessEntity> entry : set) {
            list.add(entry.getValue().toString());
        }
        return list;
    }

    @Override
    public void killProcessError(String processKey) {
        processMap.remove(processKey);
    }


}
